package com.demo.Controller;

import com.alibaba.fastjson.JSONObject;

import com.demo.Pojo.Books;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import javax.annotation.Resource;
import java.util.HashMap;


@RestController
public class Con_Controller {

    //测试Url直接写死
//    private static final String URL_PREFIX = "http://127.0.0.1:8080";

    //添加Ribbon后通过服务名进行访问实现负载均衡
    private static final String URL_PREFIX = "http://SpringCloud-Provider1";

    @Resource
    private RestTemplate template;


    /**
     * @return 参数:服务提供方地址(接口),返回类型.class,参数实体
     */
    @RequestMapping("/getAll")
    public JSONObject getAll(){
        return template.getForObject(URL_PREFIX+"/book/allBook",JSONObject.class);
    }

    //1.根据id查看

    /**
     *
     * @param id getForObject方法不可以直接传递对象和参数，可以进行拼接或者用map传参
     * @return
     */
    @RequestMapping("/getById/{id}")
    public JSONObject queryBookById(@PathVariable("id") int id){

        HashMap<String, Integer> params = new HashMap<>();
        params.put("id",id);
        return template.getForObject(URL_PREFIX+"/book/queryBookById/{id}", JSONObject.class,params);
    }

    /**
     * @param books
     * @return postForObject方法可以直接传对象
     */
    //2.添加(自增的不用设置id)
    @RequestMapping("/addBook")
    public Integer addBook(@RequestBody Books books){
        System.out.println(books);
        return template.postForObject(URL_PREFIX+"/book/addBook",books,Integer.class);
    }

    //3.修改
    @RequestMapping("/updateBook")
    public Integer updateBook(@RequestBody Books book){
        return template.postForObject(URL_PREFIX+"/book/updateBook",book,Integer.class);
    }


    //4.删除：restFul风格进行传参
    @GetMapping("/del/{BookId}")
    public Integer delBook(@PathVariable int BookId){
        System.out.println(BookId);
        return template.getForObject(URL_PREFIX+"/book/del/"+BookId,Integer.class);
    }

    //5.根据书名模糊查询
    @RequestMapping("/queryBookName/{bookName}")
    public JSONObject queryBookName(@PathVariable("bookName") String bookName){

        return template.getForObject(URL_PREFIX+"/book/queryBookName/"+bookName,JSONObject.class);
    }

}
